﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.SharePoint;
using System.Reflection;
using Microsoft.SharePoint.Utilities;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections;
using System.Data;
using Microsoft.SharePoint.Administration;
using ConsolidationTool.Common;

namespace ConsolidationTool.WebParts.Layouts.AjaxServices
{
    
    public class FSSearchEntity
    {
        public string Month { get; set; }
        public string ActionType { get; set; }
        public string Type { get; set; }
        public string SiteUrl { get; set; }
        public string RGCCategory { get; set; }
        public string Year { get; set; }
        public string CompanyCode { get; set; }
        public string Currency { get; set; }
        public string Fields { get; set; }
        public string ListTitle { get; set; }
        public string Data { get; set; }

        public DateTime ProcessData
        {
            get
            {
                DateTime dt = DateTime.Now;
                if (DateTime.TryParse(Year + "-" + Month + "-01", out dt))
                    return dt;
                else
                    return DateTime.Parse(Year + "-01-01");
            }
        }
    }
    public class ListReceiver
    {

        internal AjaxResult Excute(HttpContext context, FSSearchEntity searchEntity)
        {
            SPList list = SPContext.Current.Web.Lists.TryGetList(searchEntity.ListTitle);
            SPQuery query = new SPQuery();
            query.Query = string.Format(@"<Where>
      <And>
         <Eq>
            <FieldRef Name='Year' />
            <Value Type='Integer'>{0}</Value>
         </Eq>
         <And>
            <Eq>
               <FieldRef Name='Month' />
               <Value Type='Integer'>{1}</Value>
            </Eq>
            <Eq>
               <FieldRef Name='CoCd' />
               <Value Type='Text'>{2}</Value>
            </Eq>
         </And>
      </And>
   </Where>
 ", searchEntity.Year, searchEntity.Month, searchEntity.CompanyCode);


            var listItems = list.GetItems(query);
            bool success = listItems.Count > 0;
            string message = "";
            if (success)
            {
                searchEntity.Data = "{";
                var listitem = listItems[0];

                foreach (SPField field in listitem.ContentType.Fields)
                {
                    if (field.StaticName != "Control")
                        searchEntity.Data += string.Format("\"{0}\":\"{1}\",", field.StaticName, listitem[field.StaticName]);
                }
                searchEntity.Data = searchEntity.Data.Substring(0, searchEntity.Data.Length - 1);
                searchEntity.Data += "}";
            }
            else
            {
                message = "can not find result ...";
            }

            return new AjaxResult(success, searchEntity) { FullMsg = message };
        }
    }

    public class LoadingFile
    {

        internal AjaxResult Excute(HttpContext context, FSSearchEntity searchEntity)
        {
           // Utilities.Log("Excute in");
            try
            {
               // Utilities.Log("Url : " + SPContext.Current.Site.Url + searchEntity.SiteUrl);
                SPWeb web = SPContext.Current.Web;

              //  Utilities.Log("Begin Receive rgc list");
                SPList RGCList = web.Lists.TryGetList("RGC");
              //  Utilities.Log("RGCList is exist ? :" + (RGCList == null));
                SPQuery rgcQuery = new SPQuery()
                {
                    Query = string.Format(@" <Where>
                                              <Eq>
                                                 <FieldRef Name='Category' />
                                                 <Value Type='Choice'>{0}</Value>
                                              </Eq>
                                           </Where>
                                     ", searchEntity.RGCCategory)
                };
             //   Utilities.Log("RGCList Query loaded");
                SPListItemCollection rgcItems = null;

                if (!string.IsNullOrEmpty(searchEntity.RGCCategory))
                {
                    rgcItems = RGCList.GetItems(rgcQuery);
                }
                else
                {
                //    Utilities.Log("RGCList Query init");
                    rgcItems = RGCList.Items;
                }
                List<string> rgc = new List<string>();
              //  Utilities.Log("RGCList Count : " + rgcItems.Count);

                if (rgcItems.Count > 0)
                {
                    for (int i = 0; i < rgcItems.Count; i++)
                    {
                        rgc.Add(rgcItems[i]["RGC"] + "");
                    }
                }

              //  Utilities.Log("RGCList Count: " + rgc.Count);

                SPList list = web.Lists.TryGetList(searchEntity.ListTitle);
                SPQuery query = new SPQuery();
                query.Query = string.Format(@" <Where>
                                              <And>
                                                 <Eq>
                                                    <FieldRef Name='Year' />
                                                    <Value Type='Text'>{0}</Value>
                                                 </Eq>
                                                 <Eq>
                                                    <FieldRef Name='Company' />
                                                    <Value Type='Text'>{1}</Value>
                                                 </Eq>
                                              </And>
                                           </Where>
                                     ", searchEntity.Year, searchEntity.CompanyCode);

              //  Utilities.Log("LoadingFile List: " + list.Title);

                var listItems = list.GetItems(query);
                if (listItems.Count > 0)
                {
                //    Utilities.Log("LoadingFile List itemCount: " + listItems.Count);
                    DataTable dt = listItems.GetDataTable();
              //      Utilities.Log("LoadingFile List Contver To Datatable ");

                    var queryResult = from t in dt.AsEnumerable()
                                      where rgc.Contains(t.Field<string>("RGC"))
                                      group t by new { t1 = t.Field<string>("Year"), t2 = t.Field<string>("Period") } into m
                                      select new
                                      {
                                          Year = m.Key.t1,
                                          Period = m.Key.t2,
                                          Qty = m.Sum(n => Utilities.parseToInt(n.Field<string>("Qty"))),
                                          Salesturnover = m.Sum(n => Utilities.parseToInt(n.Field<string>("Salesturnover"))),
                                          Freight = m.Sum(n => Utilities.parseToInt(n.Field<string>("Freight"))),
                                          Packaging = m.Sum(n => Utilities.parseToInt(n.Field<string>("Packaging"))),
                                          Exportrefund = m.Sum(n => Utilities.parseToInt(n.Field<string>("Exportrefund"))),
                                          Packing = m.Sum(n => Utilities.parseToInt(n.Field<string>("Packing"))),
                                          Rebates = m.Sum(n => Utilities.parseToInt(n.Field<string>("Rebates"))),
                                          Warehouse = m.Sum(n => Utilities.parseToInt(n.Field<string>("Warehouse"))),
                                          Commissions = m.Sum(n => Utilities.parseToInt(n.Field<string>("Commissions"))),
                                          ISOtankrental = m.Sum(n => Utilities.parseToInt(n.Field<string>("ISOtankrental"))),
                                          SBEW = m.Sum(n => Utilities.parseToInt(n.Field<string>("SBEW"))),
                                          VC = m.Sum(n => Utilities.parseToInt(n.Field<string>("VC"))),
                                          VM = m.Sum(n => Utilities.parseToInt(n.Field<string>("VM"))),

                                          PlantNet = m.Sum(n => Utilities.parseToInt(n.Field<string>("PlantNet"))),
                                          Flogistics = m.Sum(n => Utilities.parseToInt(n.Field<string>("Flogistics"))),
                                          SellingCosts = m.Sum(n => Utilities.parseToInt(n.Field<string>("SellingCosts"))),
                                          Development = m.Sum(n => Utilities.parseToInt(n.Field<string>("Development"))),
                                          AdministrationCosts = m.Sum(n => Utilities.parseToInt(n.Field<string>("AdministrationCosts"))),
                                          RDexclDepreciatio = m.Sum(n => Utilities.parseToInt(n.Field<string>("RDexclDepreciatio"))),
                                          EBITDA = m.Sum(n => Utilities.parseToInt(n.Field<string>("EBITDA"))),
                                          PlantDepreciation = m.Sum(n => Utilities.parseToInt(n.Field<string>("PlantDepreciation"))),
                                          SalesDepreciation = m.Sum(n => Utilities.parseToInt(n.Field<string>("SalesDepreciation"))),
                                          AdminDepreciations = m.Sum(n => Utilities.parseToInt(n.Field<string>("AdminDepreciations"))),
                                          RDDepreciations = m.Sum(n => Utilities.parseToInt(n.Field<string>("RDDepreciations"))),
                                          TotalDEP = m.Sum(n => Utilities.parseToInt(n.Field<string>("TotalDEP"))),
                                          Operationprofit = m.Sum(n => Utilities.parseToInt(n.Field<string>("Operationprofit"))),
                                          CommercContributio = m.Sum(n => Utilities.parseToInt(n.Field<string>("CommercContributio"))),
                                          Commercialemargin = m.Sum(n => Utilities.parseToInt(n.Field<string>("Commercialemargin")))
                                      };

                 //   Utilities.Log("LoadingFile List Sumed ");

                    return new AjaxResult(true, queryResult.ToList());

                }

            }
            catch (Exception ex)
            {
                Utilities.Log(ex.Message);
                Utilities.Log(ex.StackTrace);

            }
            return new AjaxResult(false, new { Data = "{}" });
        }

    }
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class ServiceLocator : AjaxServicesBase
    {
        public override void ProcessRequest(HttpContext context)
        {

            base.ProcessRequest(context);
            AjaxResult result = new AjaxResult(false, new { Data = "" }); ;
          //  Utilities.Log("Start");
            try
            {
                //StreamReader reader = new StreamReader(context.Request.InputStream);
                //string se = HttpUtility.UrlDecode(reader.ReadToEnd());  
                string se = HttpUtility.UrlDecode(context.Request["se"]);
                FSSearchEntity searchEntity = null;
                if (!string.IsNullOrEmpty(se))
                {
                    searchEntity = (new JavaScriptSerializer()).Deserialize<FSSearchEntity>(se);
                 //   Utilities.Log("searchEntity unwarp");
                }
                switch (searchEntity.ActionType)
                {
                    case "Utility":
                        result = new ListReceiver().Excute(context, searchEntity);
                        break;
                    case "LoadingFile":
                        result = new LoadingFile().Excute(context, searchEntity);
                        break;
                    case "Calc":
                        result = new CalcServices().Excute(context, searchEntity);
                        break;
                    case "Receiver":
                        result = new ReceiverServices().Excute(context, searchEntity);
                        break;
                    case "ExchangeRate":
                        result = new ExchangeRateServices().Excute(context, searchEntity);
                        break;

                    case "Merge":
                        result = new MergeServices().Excute(context, searchEntity);
                        break;                    
                }
            }
            catch (Exception ex)
            {
                Utilities.Log(ex.Message);
                result.Data = ex;
                result.FullMsg = ex.Message;
                result.Success = false;
            }

            base.SendAjaxResult(context, result);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

}